package com.scoy.honeymei.activity.home;

import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.gson.Gson;
import com.lzy.okgo.model.HttpParams;
import com.scoy.honeymei.R;
import com.scoy.honeymei.activity.me.MeVipActivity;
import com.scoy.honeymei.adapter.MemberTicketListAdapter;
import com.scoy.honeymei.base.BaseActivity;
import com.scoy.honeymei.bean.FilmTicketListBean;
import com.scoy.honeymei.http.HpCallback;
import com.scoy.honeymei.http.HpGo;
import com.scoy.honeymei.url.MeConstant;
import com.scoy.honeymei.url.MyUrl;
import com.scoy.honeymei.utils.IntentUtil;
import com.scoy.honeymei.utils.MyUtil;
import com.scoy.honeymei.utils.SPHelper;
import com.scoy.honeymei.utils.SystemUtil;
import com.scoy.honeymei.wxapi.PayEvent;
import com.scoy.honeymei.wxapi.PayUtil;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * @ClassName: MemberTicketActivity$
 * @Description: 影院会员
 * @Author: GaoZhan
 * @CreateDate: 2019/9/2/0002$ 下午 15:28$
 * @UpdateUser: 更新者
 * @UpdateDate: 2019/9/2/0002$ 下午 15:28$
 * @UpdateRemark: 更新内容
 */
public class MemberTicketActivity extends BaseActivity {

    @BindView(R.id.back_iv)
    ImageView backIv;
    @BindView(R.id.title_tv)
    TextView titleTv;
    @BindView(R.id.sign_tv)
    TextView signTv;
    @BindView(R.id.title_llt)
    LinearLayout titleLlt;
    @BindView(R.id.normal_rv)
    RecyclerView normalRv;
    @BindView(R.id.nodata_tv)
    TextView nodataTv;
    @BindView(R.id.nor_srl)
    SmartRefreshLayout norSrl;
    private MemberTicketActivity mContext;
    private ArrayList<FilmTicketListBean.CardBean> datalist;
    private MemberTicketListAdapter memberAdapter;
    private int pageInt;
    private int payType;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.custom_activity_list15);
        ButterKnife.bind(this);
        mContext = MemberTicketActivity.this;


        initNormal();

        httplist(0);
    }

    @Override
    public void initNormal() {
        titleTv.setText("影院会员");

        MyUtil.setStatusBar(mContext, getWindow(), true, R.color.colorWhite);
        titleLlt.setPadding(0, MyUtil.getStatusBarHeight(mContext), 0, 0);

        datalist = new ArrayList<>();
        initRV();
        norSrl.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                refreshLayout.finishRefresh(1500);
                datalist.clear();
                httplist(0);

            }
        }).setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                refreshLayout.finishLoadMore(1500);
                if (pageInt == -1) {
                    MyUtil.mytoast(mContext, "没有更多了");
                } else {
                    httplist(pageInt);
                }

            }
        });

        EventBus.getDefault().register(this);
    }

    private void initRV() {
        memberAdapter = new MemberTicketListAdapter(mContext, datalist, nodataTv);
        normalRv.setLayoutManager(new LinearLayoutManager(mContext, RecyclerView.VERTICAL, false));
        normalRv.setAdapter(memberAdapter);
        memberAdapter.setOnOneClick(new MemberTicketListAdapter.OnOneClick() {
            @Override
            public void oneClick(int pos) {
                FilmTicketListBean.CardBean cardBean = datalist.get(pos);
                int type = cardBean.getType();//类型，1=普通会员卡、2=企业会员卡
                int id = cardBean.getId();
                String payThree = cardBean.getPaytype();
                if (type == 2) {
                    new AlertDialog.Builder(mContext).setTitle(cardBean.getK_tishi())
                            .setNegativeButton("取消", null)
                            .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    showdialog(id, payThree);
                                }
                            }).show();
                } else {
                    showdialog(id, payThree);
                }


            }
        });

    }

    @OnClick({R.id.back_iv, R.id.title_tv})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.back_iv:
                finish();
                break;
            case R.id.title_tv:
                break;
        }
    }

    private void httplist(int myPage) {
        HttpParams params = new HttpParams();
        params.put("page", myPage);
        HpGo.newInstance().HttpGo(this, MyUrl.FILM_TICKET_LIST, params, new HpCallback() {
            @Override
            public void onSuccess(String o) {
                FilmTicketListBean filmTicketListBean = new Gson().fromJson(o, FilmTicketListBean.class);
                int next = filmTicketListBean.getNext();
                List<FilmTicketListBean.CardBean> card = filmTicketListBean.getCard();
                pageInt = myPage + 1;
                if (next == 0) {
                    pageInt = -1;
                }
                datalist.addAll(card);

                memberAdapter.notifyDataSetChanged();


            }

            @Override
            public void onFailed(String code, String msg, String o) {
                MyUtil.mytoast(mContext, code + "," + msg);
            }

            @Override
            public void onError(int code, String errorMsg) {
                MyUtil.mytoast(mContext, errorMsg);
            }
        });

    }


    /**
     * 选择支付弹窗
     */
    private void showdialog(int tid, String payThree) {
        final Dialog dialogpay = new Dialog(this, R.style.BottomDialogStyle);
        View view = View.inflate(this, R.layout.dialog_tocheckpay, null);

        ImageView imgClose = view.findViewById(R.id.imgClose);
        Button btnSure = view.findViewById(R.id.btnSure);
        TextView alipayTv = view.findViewById(R.id.txtZhifubao);
        TextView wxpayTv = view.findViewById(R.id.txtWechat);


        imgClose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialogpay.dismiss();
            }
        });
        alipayTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                alipayTv.setSelected(true);
                wxpayTv.setSelected(false);
                payType = 1;
            }
        });
        wxpayTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                alipayTv.setSelected(false);
                wxpayTv.setSelected(true);
                payType = 2;
            }
        });


        btnSure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (payType != 0) {
                    dialogpay.dismiss();
                    buyPay(tid, payType, payThree);
                    //    IntentUtil.openAPP(mContext,"weixin://dl/businessWebview/link/?appid=wx3703bd27d5d4d848&url=1");

                }
            }
        });
        dialogpay.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
                payType = 0;
            }
        });

        dialogpay.setContentView(view);
        dialogpay.setCanceledOnTouchOutside(true);
        Window dialogWindow = dialogpay.getWindow();
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        lp.width = (int) (SystemUtil.getScreenWidth(mContext));
        lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
        lp.gravity = Gravity.BOTTOM;
        dialogWindow.setAttributes(lp);
        dialogpay.show();
    }

    private void buyPay(int tid, int payType, String payThree) {
        HttpParams params = new HttpParams();
        params.put("id", tid);
        params.put("pay_type", payType);//1=支付宝、2=微信
        params.put("uid", SPHelper.getString(MeConstant.UID, ""));
        HpGo.newInstance().HttpGo(this, MyUrl.BUY_FILMCOUNPON_BUY, params, new HpCallback() {
            @Override
            public void onSuccess(String o) {
                // payThree  1  三方； 2  原生
                if ("2".equals(payThree)) {
                    if ("false".equals(o)) {
                        MyUtil.mytoast(mContext, "支付错误");
                        return;
                    }
                    PayUtil.toPayPayPay(mContext, payType, o);//支付
                } else {
                    if (payType == 1) {
                        IntentUtil.openAPP(mContext, MyUrl.APP_OPEN_ALIPAY + o);
                        finish();
                    } else {
                        if ("false".equals(o)) {
                            MyUtil.mytoast(mContext, "支付错误");
                            return;
                        }
                        PayUtil.toPayPayPay(mContext, payType, o);//支付
                        //  IntentUtil.openAPP(mContext, MyUrl.APP_OPEN_WX + o);
                    }

                }

            }

            @Override
            public void onFailed(String code, String msg, String o) {
                MyUtil.mytoast(mContext, code + "," + msg);
            }

            @Override
            public void onError(int code, String errorMsg) {
                MyUtil.mytoast(mContext, errorMsg);
            }
        });

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onPayEvent(PayEvent event) {
        Log.d("WXPAY", "--------onPayFinish 00, errCode = " + event.toString());
        int type = event.getType();//0 成功 -1失败 -2取消
        if (type == 0) {
            MyUtil.mytoast0(mContext, "已成功领取", R.mipmap.ic_sure);
            finish();
            startActivity(new Intent(mContext, MeVipActivity.class));
        } else if (type == -1) {
            MyUtil.mytoast(mContext, "支付失败");
        } else {
            MyUtil.mytoast(mContext, "支付取消");
        }

    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

}
